package com.ylz.sjzx.sio.room.inceptor;

import com.ylz.sjzx.sio.common.core.enums.SocketModel;
import com.ylz.sjzx.sio.common.core.core.SioBase;
import com.ylz.sjzx.sio.common.core.core.container.common.annotation.AdapterDesc;
import com.ylz.sjzx.sio.common.core.core.container.common.annotation.InterceptorDesc;
import com.ylz.sjzx.sio.common.core.core.Interceptor.IInterceptor;
import com.ylz.sjzx.sio.sdk.client.core.IMNioBase;
import com.ylz.sjzx.sio.common.core.exception.CloseException;
import com.ylz.sjzx.sio.sdk.client.session.IMSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @Description: TODO
 */

@InterceptorDesc(order = 1)
public class SessionInterceptor implements IInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle() {
        IMSession session = IMNioBase.getSession();
        AdapterDesc iAdapterDesc = SioBase.getIAdapterDesc();
        if (session.isStudent() && iAdapterDesc.onlyAdmin()) {
            this.logger.error("学生不允许访问这些接口{},接口信息{}", session, iAdapterDesc);
            return false;
        }
        return true;
    }

    @Override
    public boolean postHandle() {
        this.logger.debug("SessionCacheInterceptor:postHandle");
        return true;

    }

    /**
     * 异常请求 清理session
     */
    @Override
    public void afterCompletion() {
        Throwable exception = SioBase.getException();
        if (exception != null && (exception instanceof CloseException)) {
            //主动抛出异常关闭连接
            //存在异常闭关链接
            //IMNioBase.getSession().getChannel().;
            IMSession session = IMNioBase.getSession();
            if (Objects.equals(SocketModel.channel, session.getSocketModel())) {
                session.getChannel().close();
            } else {
                session.getSocketIOClient().disconnect();
            }
        }
        this.clean();
    }

    /**
     * 上下文环境销毁
     */
    private void clean() {
        IMNioBase.clean();
        SioBase.clean();
    }
}
